<?php
header('Access-Control-Allow-Origin: *'); // to allow this code to be called from multiple places
// For high-security code, this should be fetched from the user configuration.
// So that a given username is only used from a set of allowed domains.

include 'config.php'; // Do not share config.php file with the DbDiff client.
$RepositoryDbName = '__RepositoryDb__';
$db_config = $dbs_config[$RepositoryDbName]['config'];
$mysql_last_insert_id = null; // nothing inserted yet.
$mysql_link = null;
$log = array();
if($db_config === null){
  echo "DBS_CONFIG<br><pre>".print_r($dbs_config).'</pre>';
    die("DB Config was not found - insert a Repository in DbDiff/config.php");  
}  
$config = $db_config;
if(!array_key_exists('format', $_REQUEST)){
    $_REQUEST['format']='json'; //default, since the file is called json.php
}

$_RESPONSE = array(); 
if(get_var('return_request')) // return the request if asked for this
    $_RESPONSE['request'] = $_REQUEST; // this is used e.g. to handle a selector id for get_environments

function strip_nl($str) {
    return str_replace(array("\n", "\r"), '', $str);
}

function json_log($msg){
    global $log;
    $mt = microtime();
    if(array_key_exists($mt, $log))
        $mt .= '.1';
    $log[$mt] = $msg;
}

function json_get_log(){
    global $log;
    return $log;
}

function get_var($key,$mandatory=false){
  if(array_key_exists($key,$_POST))
    return $_POST[$key];
  if(array_key_exists($key,$_GET))
    return $_GET[$key];
  if($mandatory){
      error("The field '$key' is mandatory. Execution has stopped!");
  }  
}  

function getDbRepository(){
    global $db_config,$mysql_link;
    if(!$mysql_link)
        json_log("mysql_link was null '$mysql_link' ");
    else{
        json_log("mysql_ping no link ".mysql_ping());
        json_log("mysql_ping with global link ".mysql_ping($mysql_link));
    }   
    if($mysql_link)
        return $mysql_link;
    if(!is_array($db_config)){
        error(" $db_config must be an array ",$db_config);    
    }
    return getDb($db_config);
}

function getDb($config){
    global $mysql_link;
    json_log("getting DB with getDB() $mysql_link ");
    if(!is_array($config)){
         error("Config must be an array".print_r($config));
    }
    $config['user'] or error('UserName missing');
    $config['password'] or error('Password missing');
    $config['host'] or error('Host missing');
    
    $db = @mysql_connect($config['host'], $config['user'],$config['password']);
     if (!$db) {
      error("<hr>DB Connection not created<pre>".print_r($config).'</pre>');
    }
    
    if (!mysql_select_db($config['name'], $db)) {
      error("<hr>Unable to select DB ".var_dump($config));
    }
    $mysql_link = $db;
    $mysql_ping = @mysql_ping($mysql_link);
    json_log("mysql_ping with newly createed link '$mysql_ping' ");
    return $db;  
}  
  
function error($msg){
    global $_REQUEST;
    $format = get_var('format');
    $values = get_var('values');
    $array['request'] = $_REQUEST;
    $array['error'] = $msg;
    $array['values'] = $values;
    //if($format=='json')
    {
        die(json_encode($array));
    }
    print_r($array);
    throw new exception($msg);    
}

function warning($msg){
    global $_REQUEST;    
    $array = $_REQUEST;
    $format = get_var('format');
    $array['warning'] = $msg;
    if($format=='json'){
        die(json_encode($array));
    }
    print_r($array);    
}
  
function makeQueryReturnAll($query){
    global $mysql_last_insert_id;
    $db = getDbRepository();
    if(!$db){
        error("Database not active");    
    }
    if(!$query){
        error("Query not given");
    }
    $is_insert = stripos($query,'insert');
    $result = mysql_query($query,$db);
    if(!$result){//FALSE WAS RETURNED
        $message  = 'Invalid query: ' . mysql_error() . "\n";
        $message .= 'Whole query: ' . $query;
        error("Error during mySQL Query\n".$message);
    }
    if ((mysql_num_rows($result) == 0) && $is_insert) {
        $mysql_last_insert_id = mysql_insert_id();
        return true;
        exit;
    }
    
    // While a row of data exists, put that row in $row as an associative array
    // Note: If you're expecting just one row, no need to use a loop
    // Note: If you put extract($row); inside the following loop, you'll
    //       then create $userid, $fullname, and $userstatus
    $rows = array();
    while ($row = mysql_fetch_assoc($result)) {
        $rows[] = $row;
    }    
    mysql_free_result($result);
//    mysql_close($db);
    
    return $rows;
}  

function makeQueryReturnRow($query){
    $rows = makeQueryReturnAll($query);
    if(is_array($rows))
        return reset($rows);
    return $rows;
}

function makeQueryReturnField($query,$field){
    $row = makeQueryReturnRow($query);   
    if(!is_array($row)) error("No rows  - '$query' ");
    if(!array_key_exists($field,$row)) error("Given field does not exists in query result.".var_dump($row,true));
    return $row[$field];
}


function insert_json($config,$json,$name,$application_id,$environment_id){
    $q='';
    if(is_null($json)){
        error("No JSON or Similar given in JSON var");
    }
    $db = getDb($config);
    json_log('SnapShot length is '||strlen($json));
    $result = mysql_query($q="INSERT INTO `sr_snapshots` "
            ."(`snapshot_text`, `snapshot_name`,`application_id`,`environment_id`) "
            ."VALUES ('$json', '$name','$application_id','$environment_id')");  
    if (!$result) {
        error('Could not query:  '.$q.'<hr>' . mysql_error());
    }
    json_log("Last inserted record has id ". mysql_insert_id());
    //mysql_free_result($result);
}

  /**
  func: "getLoadSnapShotFromRepository", snapshot_name: key_name 
  */
  function getLoadSnapShotFromRepository($config,$snapshot_name){
    $environment_id = get_var('environment_id');
    $application_id = get_var('application_id');
    $db = getDb($config);
    $q="SELECT * FROM `sr_snapshots` WHERE 1 ";    
    if($snapshot_name)
        $q.= "and `snapshot_name` = '$snapshot_name' ";
    if($environment_id)
        $q.= "and `environment_id` = '$environment_id' ";
    if($application_id)
        $q.= "and `application_id` = '$application_id' ";    
    $q.='ORDER BY `snapshot_id` DESC LIMIT 1 ';    
    $result = mysql_query($q);
  
   if (!$result) {
    die('Could not query:  '.$q.'<hr>' . mysql_error());
    }
  
    $row = mysql_fetch_assoc($result);
    //snapshot_text, snapshot_name, application_id
    
    mysql_free_result($result);
  
//    mysql_close($db);  
    return $row['snapshot_text'];
  }

    function createUser($user,$password){
        global $mysql_last_insert_id,$mysql_link;
        if(!$mysql_link)
            $mysql_link = getDbRepository();
        $uniqid = uniqid('SR', true);
        if(!preg_match("/^[^@]*@[^@]*\.[^@]*$/",$user)) error("Username must be valid email!");
        if(!(strlen($password)>5)) error("Password must be at least 6 letters or numbers");
        $query = sprintf("INSERT INTO `sr_users` (`user_name`,`password`,`uniqid`) VALUES('%s','%s','$uniqid') ",
            mysql_real_escape_string($user),
            mysql_real_escape_string($password));
        if(makeQueryReturnAll($query)){
            if(is_numeric($mysql_last_insert_id)){
                return  array('user_id'=>$mysql_last_insert_id,'uniqid'=>$uniqid);  
            }    
        }        
        error("Error while creating user");
    }

    function doUserLogin($user,$password){
        $user or error("No user given to doUserLogin");
        $mysql_link = getDbRepository();
        json_log("doUserLogin: mysql_link '$mysql_link' ");
        $query = sprintf("SELECT * FROM `sr_users` WHERE `user_name`='%s' AND `password`='%s'",
            mysql_real_escape_string($user,$mysql_link),
            mysql_real_escape_string($password,$mysql_link));
        $row = makeQueryReturnRow($query);
        if($row){// Is not false
            unset($row['password']); // dont return the password.
            return $row;
        }        
        error("Error while logging in");
    }

    function uniqidToUserId($uniqid){
        $mysql_link = getDbRepository();
        $query = sprintf("SELECT user_id FROM `sr_users` WHERE `uniqid`='%s' ",
            mysql_real_escape_string($uniqid,$mysql_link));
        $user_id = makeQueryReturnField($query,'user_id');
        if($user_id){// Is not false
            return $user_id;
        }        
        error("Unable to find user_id from '$uniqid' ");
    }

$json_str = "";
$json_str = get_var('JSON_DB_LAYOUT');
$func = get_var('FUNC');  
$snapshot_name= get_var('SNAPSHOT_NAME');
switch($func){
  case "getLoadSnapShotFromRepository":{
    die(getLoadSnapShotFromRepository($db_config,$snapshot_name));
    //die("End of getLoadSnapShotFromRepository($snapshot_name)");
    break;
  }
  case "doLogin":{
    $user = get_var("username") or error("No Username given");
    $password = get_var("qos") or error("No Password given");
    $_RESPONSE['row'] = doUserLogin($user,$password);    
    break;
  } 
  
  case "createEnvironment":{
      $uniqid = get_var('uniqid') or error('No Unique User ID given (\'uniqid\')');
      $environment_name = get_var('environment_name') or error('No Environment_name given');
      $next_environment_id = get_var('next_environment_id') or error('No Next Environment ID given');
      $mysql_link = getDbRepository();      
      $query = sprintf("INSERT INTO `sr_environment` (`environment_name`,`next_environment_id`,`uniqid`) VALUES('%s','%s','$uniqid') ",
            mysql_real_escape_string($environment_name,$mysql_link),
            mysql_real_escape_string($next_environment_id,$mysql_link));
      $_RESPONSE['row'] = makeQueryReturnRow($query);
      break;
  }
  
  case "getEnvironments":{
      $uniqid = get_var("uniqid");
      $mysql_link = getDbRepository();
      $user_id = uniqidToUserId($uniqid);
      $query = sprintf("SELECT * FROM `sr_environments` WHERE `user_id`='%s' ",
            mysql_real_escape_string($user_id,$mysql_link));
      $all = makeQueryReturnAll($query);
//      $ar = $_REQUEST;      
//$res = array_merge($all, $_REQUEST);
      if($all){// Is not false
           $_RESPONSE['rows'] = $all;
      }
      else{
          $_RESPONSE['query'] = $query;
          warning('You do not have any Environments - please create some');
      }
      break;
  }

   case "createApplication":{
      $uniqid = get_var('uniqid');
      $application_name = get_var('application_name');
      $mysql_link = getDbRepository();
      $user_id = uniqidToUserId($uniqid);
      $query = sprintf("INSERT INTO `sr_applications` (`application_name`,`uniqid`) VALUES('%s',$uniqid') ",
            mysql_real_escape_string($application_name,$mysql_link));
      $_RESPONSE['rows'] = makeQueryReturnRow($query);
      break;
  }
  
  case "getApplications":{
      $uniqid = get_var("uniqid");
      $mysql_link = getDbRepository();
      $user_id = uniqidToUserId($uniqid);
      $query = sprintf("SELECT * FROM `sr_applications` WHERE `user_id`='%s' ",
            mysql_real_escape_string($user_id,$mysql_link));
      $all = makeQueryReturnAll($query);
      if($all){// Is not false
        $_RESPONSE['rows'] = $all;
      }
      else{
        $_RESPONSE['query'] = $query;
          error('No Rows returned');
      }
      break;
  }

  case "doCheckUserNameExists":{
    $user = get_var("user");
    die("user loged in with $values db $db_config us $user and ps $password  ");
    //die("End of getLoadSnapShotFromRepository($snapshot_name)");          
  } 
  
    
  case "doCreateUser":{
    $user = get_var("user",true);
    $password = get_var("password",true);
    $values = get_var("values");
    $format = get_var("format");
    $newUser = createUser($user,$password);
    $values['user_id'] = $newUser['user_id'];
    $values['uniqid'] = $newUser['uniqid'];
    $values['msg']='User created succesfully';
    $_RESPONSE['row'] = $values;
    /*
    if($format=='json'){
            die(json_encode($values));
        }
    die(implode($values,'</br>'));
  //die("End of getLoadSnapShotFromRepository($snapshot_name)");  
     * 
     */ 
    break;
    }//doCreateUser
  
  case "insertSnapshot":{
    $values = get_var("values");
    $snapshot_name = get_var('snapshot_name',true);
    $snapshot_text = get_var('snapshot_text',true);
    $application_id = get_var('application_id',true);
    $environment_id = get_var('environment_id',true);
    $values = insert_json($config, $snapshot_text, $snapshot_name, $application_id, $environment_id);
    $values['user_id'] = $newUser['user_id'];
    $values['uniqid'] = $newUser['uniqid'];
    $values['msg']='User created succesfully';
    $values['snapshot_text'] = substr($snapshot_text, 0,40).'... (cropped)'; 
    //$_RESPONSE['row'] = $values;
    /*
    if($format=='json'){
            die(json_encode($values));
        }
    die(implode($values,'</br>'));
  //die("End of getLoadSnapShotFromRepository($snapshot_name)");  
     * 
     */ 
    break;
    }//doCreateUser
    
   case "insertSchema":{
        //echo "<h2>JSON DECODE</h2>$json_str<hr/>";
        $db_layout = json_decode($json_str);
        echo "Dumping layout<br/>";
        if($db_layout===null){
            echo "<br/>JSON_DB_LAYOUT was === NULL<br/>";
            $db_layout =unserialize(strip_nl(stripslashes($json_str)));
            echo "<br/> Unserializing Done<br/>";
        }
        echo "<PRE>";
        echo nl2br(print_r($db_layout,false));
        echo "</PRE>";
        ;  
        $application_id = get_env('application_id');
        $environment_id = get_env('environment_id');
        insert_json($db_config,$json_str,$snapshot_name,$application_id,$environment_id);
    }

    default:
        error("No Func choosen '$func' ");
 }
  
$_RESPONSE['log'] =  json_get_log();
$_RESPONSE['request'] = $_REQUEST;
if(array_key_exists('snapshot_text', $_REQUEST)){
    $_RESPONSE['request']['snapshot_text'] = substr($_REQUEST['snapshot_text'], 0, 100) . '... (cropped to 100 chars)'; 
}
 

if($_REQUEST['format']=='json'){
    die(json_encode($_RESPONSE));
} 
print_r($_RESPONSE);